package ru.hh.team02.chat.test;


import ru.hh.team02.chat.utils.StringSocket;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/*
 * dummy client for testing purposes
 */
public class TestClientFromFile {
    private StringSocket requestSocket;

    public static String nameClient;

    public static void main(final String args[]) {
        nameClient = args[0];
        TestClientFromFile client = new TestClientFromFile();
        client.run();
    }

    private void run() {
        try {
            requestSocket = new StringSocket(new Socket("localhost", 2004));
            System.out.println("connected to localhost in port 2004");

            BufferedReader reader = null;
            try {
                reader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(nameClient)));
            }
            catch (FileNotFoundException e1) {
                System.out.println("File not found");
            }

            String message = "";
            while ((message = reader.readLine()) != null) {

                String [] strarr = message.split(";");
                if (strarr.length == 2)
                {
                    requestSocket.write(strarr[1]);
                    Thread.sleep(Integer.parseInt(strarr[0]));
                }

                if (requestSocket.available()) {
                    handleMessage(requestSocket.read());
                }

            }
        } catch (UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host!");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (requestSocket != null) requestSocket.close();
        }
    }

    private void handleMessage(String message) {
        System.out.println(message);
    }

}
